/*
 * @Author: panzhiwei 749458928@qq.com
 * @Date: 2024-01-29 16:25:09
 * @LastEditors: panzhiwei 749458928@qq.com
 * @LastEditTime: 2024-01-31 11:16:29
 * @FilePath: /2DDemo/assets/Script/explosion.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// Explosion.ts
import { _decorator, Component, ParticleSystem, Collider2D, IPhysics2DContact,Contact2DType } from 'cc';
import { Enemy } from './Enemy/Enemy';
const { ccclass, property } = _decorator;

@ccclass('Explosion')
export class Explosion extends Component {
    @property
    public duration: number = 1; // 爆炸持续时间（秒）

    @property
    public attackPower: number = 50; // 爆炸的攻击力

    @property
    public explosionRadius: number = 100; // 爆炸半径

    // 爆炸初始化
    start() {
        // 获取粒子系统组件并开始播放
        const particleSystem = this.getComponent(ParticleSystem);
        if (particleSystem) {
            particleSystem.play();
        }

        // 对范围内的敌人造成伤害
        // this.applyDamageToEnemiesInRange();

        // 设置定时器，在爆炸持续时间后销毁对象
        this.scheduleOnce(() => {
            this.node.destroy();
        }, this.duration);
    }

    onLoad() {
        // 注册单个碰撞体的回调函数
        let collider = this.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        // 检查是否与敌人碰撞
        if (otherCollider.node.name === 'Enemy') {
            let enemyScript = otherCollider.node.getComponent(Enemy);
            if (enemyScript) {
                // 在此处实现爆炸碰到敌人后的行为
                // 例如，对敌人造成伤害
                enemyScript.explosionTakeDamage(this.attackPower);
            }
        }
    }

    // 可以添加其他方法，例如处理爆炸范围内的伤害
    // applyDamageToEnemiesInRange() {
    //     const explosionPosition = this.node.position;

    //     // 获取敌人所在的场景或父节点
    //     const scene = this.node.parent;

    //     // 检测并对范围内的敌人造成伤害
    //     scene.children.forEach(child => {
    //         if (child.name === 'Enemy' && this.node.position.distance(child.position) <= this.explosionRadius) {
    //             let enemyScript = child.getComponent(Enemy);
    //             if (enemyScript) {
    //                 enemyScript.takeDamage(this.attackPower,explosionPosition);
    //             }
    //         }
    //     });
    // }

}